package com.zc.hadoop.mapreduce3;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

/**
 * 没有Reduce实现的MapReduce
 *
 */
public class NoReduceWordCountMapReduce extends Configured implements Tool{
	
	/**
	 * Mapper
	 */
	public static class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
		// 定义map输出key、value值
		protected Text mapOutputKey = new Text();
		// 以1开始计数
		protected IntWritable mapOutputVlaue = new IntWritable(1);

		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context)
				throws IOException, InterruptedException {

			// 获取每行数据
			String lineValue = value.toString();

			System.out.println("Mapper lineValue=" + lineValue);

			// 切割数据
			StringTokenizer st = new StringTokenizer(lineValue);

			while (st.hasMoreTokens()) {
				// 获取下一个值
				String wordValue = st.nextToken();

				System.out.println("Mapper wordValue=" + wordValue);

				mapOutputKey.set(wordValue);
				context.write(mapOutputKey, mapOutputVlaue);

			}

			super.map(key, value, context);
		}

	}
	
	@Override
	public int run(String[] args) throws Exception {
		Job job = Job.getInstance(super.getConf(), NoReduceWordCountMapReduce.class.getSimpleName());
		job.setJarByClass(NoReduceWordCountMapReduce.class);
		Path inputDir = new Path(args[0]);
		FileInputFormat.addInputPath(job, inputDir);
		
		job.setMapperClass(WordCountMapper.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(IntWritable.class);
		
		// 设置reduce的任务数量为0
		// job.setNumReduceTasks(0);(优先级第二)
		Path outputDir = new Path(args[1]);
		FileOutputFormat.setOutputPath(job, outputDir);
		
		boolean flag = job.waitForCompletion(true);
		return flag ? 0 : 1;
	}
	
	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		
		conf.setInt("mapreduce.job.reduces", 0);//优先级第三
		
		int status = ToolRunner.run(conf, new NoReduceWordCountMapReduce(), args);
	}

}
